package org.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.springboot.entity.Expert;
import org.example.springboot.repository.ExpertRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.springboot.dto.ExpertDTO;
import org.example.springboot.entity.User;
import org.example.springboot.mapper.UserMapper;

import java.util.List;

@Service
public class ExpertService {
    @Autowired
    private ExpertRepository expertRepository;

    @Autowired
    private UserMapper userMapper;

    public List<Expert> findAll() {
        return expertRepository.findAll();
    }

    public Expert findById(Long id) {
        return expertRepository.findById(id).orElse(null);
    }

    public Expert save(Expert expert) {
        return expertRepository.save(expert);
    }

    public void delete(Long id) {
        expertRepository.deleteById(id);
    }

    public List<ExpertDTO> getAllExpertDTOs() {

        List<User> users = userMapper.selectList(new QueryWrapper<User>().eq("role", "EXPERT"));
        List<Expert> experts = expertRepository.findAll();
        return users.stream().map(user -> {
            ExpertDTO dto = new ExpertDTO();
            dto.setUser(user);
            experts.stream().filter(e -> e.getUserId().equals(user.getId())).findFirst().ifPresent(dto::setExpert);
            return dto;
        }).toList();
    }

    public ExpertDTO getExpertDTOByUserId(Long userId) {
        User user = userMapper.selectById(userId);
        Expert expert = expertRepository.findByUserId(userId);

        System.out.println(expert);
        ExpertDTO dto = new ExpertDTO();
        dto.setUser(user);
        dto.setExpert(expert);
        return dto;
    }

    public Expert findByUserId(Long userId) {
        return expertRepository.findByUserId(userId);
    }
} 